<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>4-getSnapshotBeforeUpdate的使用场景</title>
        <style type="text/css">
            .list {
                width: 200px;
                height: 150px;
                background-color: skyblue;
                overflow: auto;
            }

            .news {
                height: 30px;
            }
        </style>
    </head>
    <body>
        <!-- 准备好DOM容器 -->
        <div id="test"></div>

        <!-- 必须按照顺序引入JS -->
        <!-- 引入React核心库 -->
        <script src="../js/17/react.development.js"></script>
        <!-- 引入react-dom库，用于操作DOM -->
        <script src="../js/17/react-dom.development.js"></script>
        <!-- 引入babel，用于将JSX翻译为JS -->
        <script src="../js/17/babel.min.js"></script>

        <!-- type必须为text/babel，代表里面的内容为JSX -->
        <script type="text/babel">
            class NewsList extends React.Component {
                state = { newsArr: [] };

                componentDidMount() {
                    setInterval(() => {
                        const { newsArr } = this.state;

                        const news = "新闻" + (newsArr.length + 1);

                        this.setState({ newsArr: [news, ...newsArr] });
                    }, 1000);
                }

                getSnapshotBeforeUpdate() {
                    // 返回的数据会传入到componentDidUpdate()方法的第三个参数
                    return this.newsList.scrollHeight;
                }

                componentDidUpdate(prevProps, prevState, height) {
                    this.newsList.scrollTop +=
                        this.newsList.scrollHeight - height;
                }

                render() {
                    return (
                        <div className="list" ref={(c) => (this.newsList = c)}>
                            {this.state.newsArr.map((n, index) => {
                                return (
                                    <div key={index} className="news">
                                        {n}
                                    </div>
                                );
                            })}
                        </div>
                    );
                }
            }

            ReactDOM.render(<NewsList />, document.getElementById("test"));
        </script>
    </body>
</html>
